package ioStream.file.nodeStream.byteStream;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:字节输入流学习
 * User:22954
 * Date:2024-03-15
 * Time:14:19
 */
@SuppressWarnings("all")
public class FileInputStream_ {
    /*
    FileInputStream extends InputStream
    int read() throws IOException  从该输入流中读取一个字节的数据,返回数据的下一个字节(ASCII值)，如果到达文件末尾，则为返回-1
    int read(byte[] b) throws IOException  将此输入流中最多b.length字节的数据读取到字节数组中,返回读取到缓冲区的总字节数，或者-1(如果由于已到达文件末尾而没有更多数据)
     */

    @Test
    public void readFile1() {//read() 读取单字节,效率低
        String filePath = "f:/Test/NewFile3.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData);
            }
            System.out.println();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    public void readFile2() {//read(byte[] b) 按设定字节数读取,效率高
        String filePath = "f:/Test/NewFile3.txt";
        byte[] buf = new byte[8];
        int readlen = 0;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readlen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readlen));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
